from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from bs4 import BeautifulSoup
import time
import subprocess
from datetime import datetime

print('---------')

def DoLog(isSuccess):
    dt = datetime.now()
    strformat =  dt.strftime("%Y-%M-%d-%H-%m")
    
    if isSuccess==True:
        logfile = open('./logs/'+strformat+'.txt','w')
        logfile.write('')
        logfile.close()
    else:
        logfile = open('./logs/'+strformat+'.txt','w')
        logfile.write('')
        logfile.close()
    

# Chrome
chrome_options = Options()

#chrome_options.add_argument('--headless')
#chrome_options.add_argument('--no-sandbox')
#chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('user-data-dir=/home/wdnm/.mozilla/firefox/br20yo5m.default-release')
#profile = webdriver.FirefoXProfile(f'/home/wdnm/.mozilla/firefox/br20yo5m.default-release')
# Chrome
browser = webdriver.Firefox(firefox_profile='/home/wdnm/.mozilla/firefox/br20yo5m.default-release')

browser.get('https://space.bilibili.com/316568752')

browser.refresh()

# 
browser.implicitly_wait(30)

time.sleep(10)  # import time

browser.refresh()

time.sleep(15)

file = open('test.html','w')

file.write(browser.page_source)

file.close()

# time.sleep(120)

soup = BeautifulSoup(browser.page_source, "html.parser")


latest_tag = soup.find('span', string='最多收藏')

print(latest_tag)
# 10a
A_tags = latest_tag.find_all_next('a',limit=5)

print(A_tags)

realtag = A_tags[2]

video_href = realtag['href']
video_title = realtag['title']

lastfile = open('lastVideoName.txt','r')
context = lastfile.read()
lastfile.close()

if context==video_title:
    print('')
    DoLog(False)
else:
    print('you-get')
    # 
    subprocess.run(['bash','test.sh','https:'+video_href])
    # 
    updatefile = open('lastVideoName.txt','w')
    updatefile.write(video_title)
    updatefile.close()
    DoLog(True)





# 
html = browser.page_source
print('start script')
browser.quit()
